from django.shortcuts import render,reverse,redirect
from django.views import View
from teacher_front.form import Teacher_login
from django.contrib.auth.hashers import check_password
from teacher_front.models import Teachers
from django.contrib import messages
from student_front.models import Students
from student_front.forms import Students_login

class Index(View):
    def get(self,request):
        return render(request,'index.html')
    def post(self,request):
        option = request.POST.get('option')
        if option == 'teacher':
            form = Teacher_login(request.POST)
            if form.is_valid():
                num = form.cleaned_data.get('number')
                password = form.cleaned_data.get('password')
                teacher = Teachers.objects.filter(number=num).first()
                if teacher:
                    relpassword = teacher.password
                    if check_password(password,relpassword):
                        request.session['user_id'] = teacher.number
                        request.session['user_type'] = 'teacher'
                        request.session.set_expiry(0)
                        return redirect(reverse('teacher:dashbord'))
                    else:
                        messages.info(request,'密码错误!')
                        return redirect(reverse('index'))
                else:
                    messages.info(request,'用户不存在')
                    return redirect(reverse('index'))
            else:
                erros = form.get_error()
                for erro in erros:
                    messages.info(request, erro)
                    return redirect(reverse('index'))



        elif option == 'student':
            form = Students_login(request.POST)
            if form.is_valid():
                num = form.cleaned_data.get('number')
                password = form.cleaned_data.get('password')
                student = Students.objects.filter(number=num).first()
                if student:
                    relpassword = student.password
                    if check_password(password, relpassword):
                        request.session['user_id'] = student.number
                        request.session['user_type'] = 'student'
                        request.session.set_expiry(0)
                        return redirect(reverse('student:dashbord'))
                    else:
                        messages.info(request,'密码错误!')
                        return redirect(reverse('index'))
                else:
                    messages.info(request, '用户不存在')
                    return redirect(reverse('index'))
            else:
                erros = form.get_error()
                for erro in erros:
                    messages.info(request, erro)
                    return redirect(reverse('index'))

